%%%-------------------------------------------------------------------
%% @doc chat private supervisor.
%% @end
%%%-------------------------------------------------------------------

-module(chat_private_sup).

-behaviour(supervisor).

-export([ start_link/1
        , init/1
        ]).

-export([ find_child/1 ]).

start_link(Config) ->
    supervisor:start_link({local, ?MODULE}, ?MODULE, [Config]).

%% sup_flags() = #{strategy => strategy(),         % optional
%%                 intensity => non_neg_integer(), % optional
%%                 period => pos_integer()}        % optional
%% child_spec() = #{id => child_id(),       % mandatory
%%                  start => mfargs(),      % mandatory
%%                  restart => restart(),   % optional
%%                  shutdown => shutdown(), % optional
%%                  type => worker(),       % optional
%%                  modules => modules()}   % optional
init([Config]) ->
    SupFlags = 
        #{ strategy     => one_for_one
         , intensity    => 0
         , period       => 1
         },

    Amount = maps:get(mail_mailbox_process_amount, Config, 10),
    F = fun(Id) ->
            #{ id => {chat_private_worker, Id}
             , start => {chat_private_worker, start_link, [[Id, Config]]}
             , restart => transient
             , shutdown => 1000
             , type => worker
             , modules => [chat_private_worker]
             }
        end,
    ChildSpecs = [ F(Id) || Id <- lists:seq(0, Amount - 1) ],

    {ok, {SupFlags, ChildSpecs}}.


%% -spec find_child(Id) -> pid().
find_child(Id) ->
    ChildList = supervisor:which_children(?MODULE),
    find_child(Id, ChildList).

find_child(Id, [{{chat_private_worker, Id}, Pid, _, _} | _]) ->
    {ok, Pid};
find_child(_, []) ->
    undefined;
find_child(Id, [_ | ChildList]) ->
    find_child(Id, ChildList).

%% internal functions


